package com.it.schoolbookshop_back.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.schoolbookshop_back.entities.po.Book;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.vo.user.UserResetPwd;
import com.it.schoolbookshop_back.entities.vo.user.UserStatistics;
import com.it.schoolbookshop_back.entities.vo.user.UserUpdateRole;
import com.it.schoolbookshop_back.entities.vo.user.UserUpdateStatus;
import com.it.schoolbookshop_back.enums.UserRoleEnums;
import com.it.schoolbookshop_back.enums.UserStatusEnums;
import com.it.schoolbookshop_back.mapper.AdminUserManageMapper;
import com.it.schoolbookshop_back.mapper.BookMapper;
import com.it.schoolbookshop_back.mapper.FavoriteMapper;
import com.it.schoolbookshop_back.service.AdminUserManageService;
import com.it.schoolbookshop_back.service.BookService;
import com.it.schoolbookshop_back.utils.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.YearMonth;
import java.util.List;

@Slf4j
@Service
public class AdminUserManageServiceImpl implements AdminUserManageService {
    @Autowired
    private AdminUserManageMapper adminMapper;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Autowired
    private BookService bookService;
    
    @Autowired
    private FavoriteMapper favoriteMapper;

    /**
     * 管理员获取用户信息
     *
     * @param page   页码，默认1
     * @param limit  每页数量，默认10
     * @param query  搜索关键词（查询用户名、真实姓名、学号）
     * @param status 筛选状态('active', 'suspended', 'deleted')
     * @param role   筛选角色('student', 'admin')
     * @param sortBy 排序字段('created_at', 'username', 'login_at')
     * @return
     */
    @Override
    public PageBean<User> getUserInform(Integer page, Integer limit, String query, String status, String role, String sortBy) {
        PageHelper.startPage(page, limit);
        List<User> userInform = adminMapper.getUserInform(query, status, role, sortBy);
        Page<User> p = (Page<User>) userInform;
        PageBean<User> pageBean = new PageBean<>(p.getTotal(), p.getResult());
        System.out.println("pageBean = " + pageBean);
        return pageBean;
    }

    /**
     * 管理员获取用户详情
     *
     * @param id
     * @return
     */
    @Override
    public User getUserDetail(int id) {
        User user = adminMapper.getUserById(id);
        return user;
    }

    /**
     * 修改用户状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public UserUpdateStatus updateUserStatus(int id, String status) {
        adminMapper.updateStatusById(id, status);
        User userInfo = adminMapper.getUserById(id);

        return UserUpdateStatus.builder()
                .id(id)
                .username(userInfo.getUsername())
                .status(status)
                .build();
    }

    /**
     * 重置用户密码
     *
     * @param id
     * @param resetPassword
     * @return
     */
    @Override
    public UserResetPwd resetUserPassword(int id, String resetPassword) {
        adminMapper.ResetUserPwdById(id, resetPassword);
        User userInfo = adminMapper.getUserById(id);
        return UserResetPwd.builder()
                .id(id)
                .username(userInfo.getUsername())
                .newPassword(userInfo.getPassword())
                .build();

    }

    /**
     * 修改用户角色
     *
     * @param id
     * @param role
     * @return
     */
    @Override
    public UserUpdateRole updateUserRole(int id, String role) {
        adminMapper.UserUpdateRoleById(id, role);
        User userInfo = adminMapper.getUserById(id);

        return UserUpdateRole.builder()
                .id(id)
                .username(userInfo.getUsername())
                .role(userInfo.getRole())
                .build();
    }

    /**
     * 获取用户统计数据
     *
     * @return
     */
    @Override
    public UserStatistics getUserStatistics() {
        //获取当前年月
        YearMonth currentYearMonth = YearMonth.now();
        System.out.println("当前年月: " + currentYearMonth); // 格式: 2023-11
        //获取全部用户
        List<User> userList = adminMapper.getAllUser();
        int totalUsers = userList.size();
        //计算正常用户
        int activeUsers = 0;
        int suspendedUsers = 0;
        int deletedUsers = 0;
        int adminUsers = 0;
        int studentUsers = 0;
        int monthlyNewUsers = 0;
        int monthlyActiveUsers = 0;

        for (User user : userList) {
            if (user.getStatus().equals(UserStatusEnums.ACTIVE.name().toLowerCase())) {
                activeUsers++;
            }
            if (user.getStatus().equals(UserStatusEnums.SUSPENDED.name().toLowerCase())) {
                suspendedUsers++;
            }
            if (user.getStatus().equals(UserStatusEnums.DELETED.name().toLowerCase())) {
                deletedUsers++;
            }
            if (user.getRole().equals(UserRoleEnums.ADMIN.name().toLowerCase())) {
                adminUsers++;
            }
            if (user.getRole().equals(UserRoleEnums.STUDENT.name().toLowerCase())) {
                studentUsers++;
            }
        }
        //获取本月新增用户
        List<User> monthlyNewUserList = adminMapper.getMonthlyNewUsers(currentYearMonth.toString());
        monthlyNewUsers = monthlyNewUserList.size();
        // 获取本月登录过的用户
        List<User> monthlyActiveUserList = adminMapper.getMonthlyActiveUsers(currentYearMonth.toString());
        monthlyActiveUsers = monthlyActiveUserList.size();


        return UserStatistics.builder()
                .totalUsers(totalUsers)
                .activeUsers(activeUsers)
                .suspendedUsers(suspendedUsers)
                .deletedUsers(deletedUsers)
                .adminUsers(adminUsers)
                .studentUsers(studentUsers)
                .monthlyNewUsers(monthlyNewUsers)
                .monthlyActiveUsers(monthlyActiveUsers)
                .build();
    }

    /**
     * 删除用户
     *
     * @param id 用户ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUser(int id) {
        log.info("执行删除用户操作, ID: {}", id);
        try {
            // 检查用户是否存在
            User user = adminMapper.getUserById(id);
            if (user == null) {
                log.warn("要删除的用户不存在, ID: {}", id);
                return false;
            }
            
            // 直接删除用户记录
            adminMapper.deleteUserById(id);
            
            // 验证用户是否已被删除
            User deletedUser = adminMapper.getUserById(id);
            boolean success = deletedUser == null;
            
            if (success) {
                log.info("用户删除成功, ID: {}", id);
            } else {
                log.warn("用户删除失败, ID: {}", id);
            }
            
            return success;
        } catch (Exception e) {
            log.error("删除用户失败, ID: {}, 错误: {}", id, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 删除用户发布的所有书籍
     *
     * @param userId 用户ID
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public boolean deleteUserBooks(int userId) {
        log.info("开始删除用户{}的所有书籍", userId);
        try {
            // 1. 获取用户发布的所有书籍
            List<Book> userBooks = bookService.getBooksBySeller(userId, null);
            
            if (userBooks == null || userBooks.isEmpty()) {
                log.info("用户{}没有发布任何书籍", userId);
                return true; // 无书籍要删除，视为成功
            }
            
            log.info("用户{}共有{}本书籍需要删除", userId, userBooks.size());
            
            // 2. 逐个删除书籍（包含级联删除收藏记录）
            int successCount = 0;
            for (Book book : userBooks) {
                try {
                    boolean deleted = bookService.deleteBook(book.getId());
                    if (deleted) {
                        successCount++;
                    }
                } catch (Exception e) {
                    log.error("删除书籍时出错: ID={}, 标题={}, 错误: {}", 
                             book.getId(), book.getTitle(), e.getMessage());
                }
            }
            
            log.info("用户{}的书籍删除完成, 成功: {}/总数: {}", userId, successCount, userBooks.size());
            
            // 3. 判断是否全部删除成功
            return successCount == userBooks.size();
            
        } catch (Exception e) {
            log.error("删除用户{}的书籍时出错: {}", userId, e.getMessage(), e);
            return false;
        }
    }
}
